import json
import os
import logging

# 创建日志记录器
def create_logger():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s | 文件:%(filename)s,函数:%(funcName)s')
    return logging.getLogger()

# 加载语言数据
def load_language_data():
    default_language_data = {
        "current_language": "en",
        "en": {
            "app_title": "Image Processor",
            "file": "File",
            "open_original": "Open as Original",
            "open_grayscale": "Open as Grayscale",
            "merge_channels": "Merge Channels",
            "save_image": "Save Image",
            "exit": "Exit",
            "language": "Language",
            "info": "Info",
            "details": "Details",
            "edit": "Edit",
            "crop": "Crop",
            "reset": "Reset",
            "split": "Split",
            "split_channels": "Split Channels",
            "confirm_restart": "Confirm Restart",
            "restart_warning": "Please restart the application to apply the language changes.",
            "error": "Error",
            "no_image_loaded": "No image loaded.",
            "no_image_to_be_saved": "No image to be saved.",
            "no_image_to_be_cropped": "No image to be cropped.",
            "no_crop_area": "No crop area selected.",
            "no_reset_image": "No image to reset.",
            "single_file_error": "Please select more than one file to merge.",
            "single_channel_error": "The image is already a single channel.",
            "channel_saved": "Channel {} saved to {}.",
            "crop_failed": "Crop operation failed.",
            "brightness_adjust": "Adjust Brightness",
            "brightness_value": "Brightness value:",
            "apply": "Apply",
            "no_image_to_be_adjusted": "No image to adjust brightness.",
            "invalid_brightness_value": "Invalid brightness value. Please enter an integer.",
            # 新增阈值处理相关键值对
            "threshold_processing": "Threshold Processing",
            "global_threshold": "Global Threshold",
            "threshold": "Threshold",
            "threshold_requires_grayscale": "Threshold processing requires a grayscale image",
            "threshold_applied": "Global threshold applied with value: {0}",
            "reset": "Reset"
        },
        "zh": {
            "app_title": "图像处理器",
            "file": "文件",
            "open_original": "以原始格式打开",
            "open_grayscale": "以灰度格式打开",
            "merge_channels": "合并通道",
            "save_image": "保存图像",
            "exit": "退出",
            "language": "语言",
            "info": "信息",
            "details": "详细信息",
            "edit": "编辑",
            "crop": "裁剪",
            "reset": "重置",
            "split": "分割",
            "split_channels": "分割通道",
            "confirm_restart": "确认重启",
            "restart_warning": "请重启应用程序以应用语言更改。",
            "error": "错误",
            "no_image_loaded": "没有加载图像。",
            "no_image_to_be_saved": "没有图像可保存。",
            "no_image_to_be_cropped": "没有图像可裁剪。",
            "no_crop_area": "没有选择裁剪区域。",
            "no_reset_image": "没有图像可重置。",
            "single_file_error": "请选择多个文件进行合并。",
            "single_channel_error": "图像已经是单通道。",
            "channel_saved": "通道 {} 已保存到 {}。",
            "crop_failed": "裁剪操作失败。",
            "brightness_adjust": "亮度调整",
            "brightness_value": "亮度值:",
            "apply": "应用",
            "no_image_to_be_adjusted": "没有可调整亮度的图像。",
            "invalid_brightness_value": "无效的亮度值。请输入一个整数。",
            # 新增阈值处理相关键值对
            "threshold_processing": "阈值处理",
            "global_threshold": "全局阈值处理",
            "threshold": "阈值",
            "threshold_requires_grayscale": "阈值处理只能在灰度图像上进行",
            "threshold_applied": "全局阈值处理已应用，阈值: {0}",
            "reset": "重置"
        }
    }

    if os.path.exists('language.json') and os.path.getsize('language.json') > 0:
        with open('language.json', 'r', encoding='utf-8') as f:
            try:
                language_data = json.load(f)
                # 确保 'current_language' 键存在
                if 'current_language' not in language_data:
                    language_data['current_language'] = 'en'
                # 合并默认语言数据中的缺失项，只处理语言字典（忽略"current_language"等其他键）
                for lang in ['en', 'zh']:
                    if lang in default_language_data:
                        if lang not in language_data:
                            language_data[lang] = default_language_data[lang]
                        else:
                            # 确保是字典类型才进行合并
                            if isinstance(language_data[lang], dict):
                                for key, value in default_language_data[lang].items():
                                    if key not in language_data[lang]:
                                        language_data[lang][key] = value
                            else:
                                # 如果不是字典，直接替换
                                language_data[lang] = default_language_data[lang]
                return language_data
            except json.JSONDecodeError:
                logging.error("JSONDecodeError: Could not parse the file")
                return default_language_data
    else:
        logging.warning("File does not exist or the file is empty")
        return default_language_data

# 写入语言数据
def write_language_data(language_data, key, value):
    language_data[key] = value
    with open('language.json', 'w', encoding='utf-8') as f:
        json.dump(language_data, f, ensure_ascii=False, indent=4)

# 定义 is_bgr 函数
def is_bgr(image):
    """
    判断图像是否为 BGR 颜色模式
    :param image: 输入的图像
    :return: 如果是 BGR 模式返回 True，否则返回 False
    """
    if len(image.shape) == 3:
        return True
    return False
#################### 以下是载入代码 ####################
logging = create_logger()
language_data = load_language_data()